package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    /**
     * 商品上下架
     *
     * @param id     商品ID
     * @param status 商品状态 1-正常，2-下架，3-删除
     */
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        this.update().set("status", status).eq("id", id).update();
        log.info("update item status, id => {}, status => {}", id, status);
        // TODO: 商品修改后需要存储到消息队列，之后同步ES
    }

    /**
     * 扣除库存
     *
     * @param itemId
     * @param num
     */
    @Transactional
    @Override
    public void deductStock(Long itemId, Integer num) {
        try {
            update().setSql("stock = stock - " + num).set("update_time", new Date()).eq("id", itemId).update();
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
    }

    @Transactional
    @Override
    public void addStock(Long itemId, Integer num) {
        try {
            update().setSql("stock = stock + " + num).set("update_time", new Date()).eq("id", itemId).update();
        } catch (Exception e) {
            log.error("添加库存失败, {}", e.getMessage());
        }
    }
}
